<template>
  <edit-connection ref="editConnection" :local="local" />
  <point-relocate ref="pointRelocate" @update="update" />
  <add-pose ref="addPose" @update="update" />
  <q-dialog
    v-model="visible"
    seamless
    :position="$q.screen.lt.sm ? 'top' : 'right'"
  >
    <q-card style="width: 10rem">
      <q-card-section class="row items-center no-wrap">
        <div class="text-h6 text-grey">连线管理</div>
        <q-space />
        <q-btn flat round icon="close" v-close-popup />
      </q-card-section>
      <q-separator />
      <q-card-section>
        <q-list
          bordered
          separator
          dense
          style="overflow: auto; max-height: 30vh"
        >
          <q-item
            v-for="(item, index) in pointList"
            v-bind:key="index"
            @click="editPoint(item, index)"
            clickable
            v-ripple
            :active="activePoint === item.id"
            active-class="bg-teal-6 text-white"
          >
            <q-item-section>{{ item.name }}</q-item-section>
          </q-item>
        </q-list>
      </q-card-section>
      <q-separator />
      <q-card-section
        v-if="!local && online"
        class="row q-gutter-y-sm justify-center"
      >
        <q-btn
          color="primary"
          class="full-width"
          @click="local ? save() : savePoints()"
          icon="save"
          label="保存连线"
        />
        <q-btn
          color="primary"
          class="full-width"
          @click="load"
          icon="get_app"
          label="重载连线"
        />
        <q-btn
          color="secondary"
          class="full-width"
          @click="
            addPose.show();
            visible = false;
            editConnection.visible = false;
          "
          icon="add"
          label="点位添加"
        />
        <q-btn
          color="secondary"
          class="full-width"
          @click="
            pointRelocate.show(activePoint);
            visible = false;
            editConnection.visible = false;
          "
          icon="location_on"
          label="点位定位"
          v-if="activePoint !== ''"
        />
        <q-btn
          color="negative"
          class="full-width"
          @click="clear"
          icon="clear"
          label="清除连线"
        />
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script>
import { ref, inject, onMounted, watch, provide } from "vue";
import { useQuasar } from "quasar";

import EditConnection from "components/rosMapRemote/pose/EditRoute.vue";
import { api } from "boot/axios.js";
import { useAPIStore } from "stores/api";
import PointRelocate from "components/rosMapRemote/pose/PointRelocate.vue";
import AddPose from "components/rosMapRemote/pose/AddPose.vue";

export default {
  name: "PoseRoute",
  components: {
    AddPose,
    PointRelocate,
    EditConnection,
  },
  props: {
    mapId: String,
    local: { type: Boolean, default: false },
  },
  setup(props) {
    const $q = useQuasar();
    const pixiMap = inject("pixiMap");
    const pointList = inject("pointList");
    const online = inject("online");

    const mapFunction = inject("mapFunction");
    watch(mapFunction, (value) => {
      if (value !== "poseRoute") visible.value = false;
    });

    const visible = ref(false);
    const editConnection = ref();
    // 退出时取消所有
    watch(visible, (value) => {
      if (!value) {
        editConnection.value.visible = false;
      }
    });
    // 选中的点
    const activePoint = ref("");

    // 从数据库加载
    const loadRoutes = inject("loadRoutes");
    const drawRoutes = inject("drawRoutes");

    provide("loadPoints", load);
    function load() {
      loadRoutes();
      editConnection.value.visible = false;
      $q.notify({ message: "重载路线成功", type: "positive" });
      api
        .get(useAPIStore().centerUrl + "navigation/reset/" + props.mapId)
        .then((rs) => {
          if (rs.data === "done") {
            $q.notify({ message: "调度系统点位已重载", type: "positive" });
          } else {
            $q.notify({ message: "调度系统点位重载失败", type: "negative" });
          }
        });
    }

    onMounted(() => {
      if (!props.local) setTouchPoint();
    });

    function setTouchPoint() {
      // 获取点击当前点位精灵
      pixiMap.checkPoint = (pos) => {
        mapFunction.value = "poseRoute";
        // 显示点位列表
        visible.value = true;
        activePoint.value = pos.id;
        pixiMap.highlight(activePoint.value);
        pixiMap.lookAt(pos.pose.position);
        // 高亮的点显示
        // 循环获取当前点击的坐标
        for (let i = 0, iLen = pointList.value.length; i < iLen; i++) {
          if (pointList.value[i].id === pos.id) {
            editConnection.value.show(i);
          }
        }
      };
    }

    return {
      PixiMap: pixiMap,
      visible,
      pointList,
      activePoint,
      editConnection,
      savePoints: props.local ? null : inject("savePoints"),
      online,
      show() {
        activePoint.value = "";
        setTouchPoint();
        mapFunction.value = "poseRoute";
        visible.value = true;
      },
      editPoint(item, index) {
        activePoint.value = item.id;
        pixiMap.highlight(activePoint.value);
        pixiMap.lookAt(item.pose.position);
        editConnection.value.show(index);
      },
      load,
      clear() {
        pointList.value.forEach((item) => {
          item.connectedPose = [];
        });
        drawRoutes(pointList.value);
        editConnection.value.visible = false;
      },
      pointRelocate: ref(),
      update() {
        visible.value = true;
        activePoint.value = "";
      },
      addPose: ref(),
      save() {
        console.log("save");
        api
          .put(
            useAPIStore().mapUrl + "mapPose/ros/" + props.mapId,
            pointList.value
          )
          .then(() => {
            loadRoutes();
            $q.notify({ message: "重载点位成功", type: "positive" });
            api
              .get(useAPIStore().centerUrl + "navigation/reset/" + props.mapId)
              .then((rs) => {
                if (rs.data === "done") {
                  $q.notify({
                    message: "调度系统点位已重载",
                    type: "positive",
                  });
                } else {
                  $q.notify({
                    message: "调度系统点位重载失败",
                    type: "negative",
                  });
                }
              });
            visible.value = false;
          })
          .catch((err) => {
            console.error(err);
            $q.notify({ message: "保存失败", type: "negative" });
          });
      },
    };
  },
};
</script>
